<template>
  <div>
    <navBar>
      <template v-slot:default>图书分类</template>
    </navBar>

    <div id="mainbox">
      <!-- 顶部排序区域 -->
      <div class="ordertab">
        <van-tabs v-model:active="active" @click-tab="tabClick">
          <van-tab title="销量排序"></van-tab>
          <van-tab title="价格排序"></van-tab>
          <van-tab title="评论排序"></van-tab>
        </van-tabs>
      </div>
      <!-- 左侧菜单栏 -->
      <van-sidebar class="leftmenu" v-model="activeKey">
        <van-collapse v-model="activeName" accordion>
          <van-collapse-item
          v-for="(item) in categories" 
          :key="item.id"
          :title="item.name"
          :name="item.name"
          >
            <van-sidebar-item 
            v-for="(sub) in item.children" 
            :key="sub.id" 
            :title="sub.name"
            @click="getGoods(sub.id)"
             />
          </van-collapse-item>
        </van-collapse>
      </van-sidebar>
      <!-- 右侧商品区域 -->
      <div class="goodslist" ref="goodslist">
        <div class="content">
          <van-card
            v-for="item in showGoods" :key="item.id"
            :num="item.comments_count"
            :tag="item.comments_count >= 0 ? '流行' : '标签'"
            :price="item.price"
            :desc="item.updated_at"
            :title="item.title"
            :thumb="item.cover_url"
            :lazy-load="true"
            @click="itemClick(item.id)"
          />
        </div>
      </div>
    </div>

    <BackTop v-show="isShowBackTop" @bTop="bTop"></BackTop>
  </div>
</template>

<script>
import { ref,onMounted, reactive, computed,watchEffect,nextTick } from 'vue'
import {getCategory,getCategoryGoods} from '@/network/category.js'
import navBar from 'components/common/navbar/NavBar.vue'
import BackTop from 'components/common/backtop/BackTop.vue'
import BSCroll from 'better-scroll'
import Pullup from '@better-scroll/pull-up'
import { useRouter } from 'vue-router'


export default {
  name: 'Category',
  setup() {
    let isShowBackTop = ref(false)
    let active = ref(0)
    let activeKey = ref(0);
    let categories = ref([])
    let activeName = ref(1)
    let currentOrder = ref('sales') // 当前的排序条件
    let currentCid = ref(0) // 当前二级分类的 id
    const goodslist = ref(null)
    let bscroll
    const router = useRouter()

    // 商品数据模型
    const goods = reactive({
      sales: {page: 1, list:[]},
      price: {page: 1, list:[]},
      comments_count: {page: 1, list:[]}
    }) 
    // console.log(goods);

    // 点击哪个排序，就展示哪个数据
    const showGoods = computed(()=>{
      return goods[currentOrder.value].list
    })

    // 获取分类数据
    const init = async ()=>{
      const salesData = await getCategoryGoods('sales', currentCid.value)
      goods.sales.list = salesData.goods.data

      const priceData = await getCategoryGoods('price', currentCid.value)
      goods.price.list = priceData.goods.data

      const comments_countData = await getCategoryGoods('comments_count', currentCid.value)
      goods.comments_count.list = comments_countData.goods.data

    }

    onMounted(async ()=>{
      // 请求图书分类数据
      const data = await getCategory()
      categories.value = data.categories
      init()


      // 创建 BetterScroll 对象
      bscroll = new BSCroll(goodslist.value, {
        // 获取到最外层元素
        probeType: 3, // 0,1,2,3, 3 只要在运行就触发 scroll 事件
        click: true, // 是否允许点击
        pullUpLoad: true, // 上拉加载更多，默认 false
      })

      bscroll.on('scroll', (position)=>{
        // console.log(banref.value.offsetHeight);
        // console.log(position.y);
        isShowBackTop.value =  (-position.y) > 300
      })

      // 上拉加载数据，触发 pullingUp
      bscroll.on('pullingUp', ()=>{
        // console.log('上拉加载更多。。');

        const page = goods[currentOrder.value].page + 1
        getCategoryGoods(currentOrder.value, currentCid.value, goods[currentOrder.value].page).then(res=>{
          goods[currentOrder.value].list.push(...res.goods.data)
          goods[currentOrder.value].page += 1
        })
        

        bscroll.finishPullUp()
        
        nextTick(()=>{
          // 重新计算高度
          bscroll &&  bscroll.refresh()
        })

      })


    })

    // 排序选项卡
    // vant 组件自带 click-tab 事件，可以获取当前点击tab的信息 ,name 为当前索引
    const tabClick = async ({name})=>{
      let order = ['sales', 'price', 'comments_count']
      currentOrder.value = order[name]
      const Data = await getCategoryGoods(currentOrder.value, currentCid.value)
      goods[currentOrder.value].list = Data.goods.data
      nextTick(()=>{
        // 重新计算高度
       bscroll &&  bscroll.refresh()
      })
      // console.log('当前分类id：'+currentCid.value);
      // console.log('排序的序号：' + currentOrder.value);
    }

    // 通过分类得到商品
    const getGoods = (cid)=>{
      currentCid.value = cid
      init()
      // console.log('当前分类id：'+currentCid.value);
      // console.log('排序的序号：' + currentOrder.value);
    }

    // 监听任何一个变量有触发
    watchEffect(()=>{
      nextTick(()=>{
        // 重新计算高度
       bscroll &&  bscroll.refresh()
      })
    })

    const bTop = ()=>{
      bscroll.scrollTo(0, 0, 500)
    }

    return {
      activeKey,
      categories,
      activeName,
      active,
      currentOrder,
      currentCid,
      goods,
      showGoods,
      goodslist,
      bscroll,
      tabClick,
      getGoods,
      isShowBackTop,
      bTop,
      itemClick:(id)=>{
        router.push({path: '/detail', query: {id}})
      }
    }
  },
  components:{
    navBar,
    BackTop
  }
}
</script>

<style lang="scss" scoped>
#mainbox {
  margin-top: 45px;
  display: flex;
  .ordertab{
    flex: 1;
    float: right;
    height: 50px;
    z-index: 9;
    position: fixed;
    top: 45px;
    right: 0;
    left: 130px;
    
  }
  .leftmenu {
    position: fixed;
    top: 95px;
    left: 0;
    width: 130px;
    height: 100%;
    

  }
  .goodslist {
    flex: 1;
    position: absolute;
    top :100px;
    left: 130px;
    right: 0;
    height: 100vh;
    padding: 10px;
    text-align: left !important;
    // .content {
    //   // padding-top: 100px;
    // }
  }
}

::v-deep .van-card__thumb {
  width: 78px;
}

</style>
